/*
 *  Copyright (C) 2010-2012 Taylor Leese (tleese22@gmail.com)
 *
 *  This file is part of jappstart.
 *
 *  jappstart is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  jappstart is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with jappstart.  If not, see <http://www.gnu.org/licenses/>.
 */
package wendyeq.iweb.blog.web.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.springframework.context.MessageSource;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.LocaleResolver;

import wendyeq.iweb.blog.exception.DuplicateUserException;
import wendyeq.iweb.blog.pojo.UserAccount;
import wendyeq.iweb.blog.service.EnhancedUserDetailsService;
import wendyeq.iweb.blog.service.IUserAccountService;
import wendyeq.iweb.blog.vo.Register;

import com.google.appengine.api.memcache.Expiration;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;


/**
 * The registration controller.
 */
@Controller
@SessionAttributes(RegisterController.REGISTER)
public class RegisterController {
	private static final Logger logger = Logger
	.getLogger(RegisterController.class);

	/**
	 * The register form attribute name.
	 */
	protected static final String REGISTER = "register";
	@Resource(name="passwordEncoder")
	private PasswordEncoder passwordEncoder;

	@Resource(name="userDetailsService")
	private EnhancedUserDetailsService userDetailsService;

	@Resource(name="localeResolver")
	private LocaleResolver localeResolver;

	@Resource(name="userAccountServiceImpl")
	private IUserAccountService userAccountService;
	/**
	 * The message source.
	 */
	@Resource(name="messageSource")
	private MessageSource messageSource;

	
	private MemcacheService memcacheService;

	
	public MemcacheService getMemcacheService() {
		return MemcacheServiceFactory.getMemcacheService();
	}

	public void setMemcacheService(MemcacheService memcacheService) {
		this.memcacheService = memcacheService;
	}

	/**
	 * Display the create account form.
	 *
	 * @param model the model map
	 * @return the view name
	 */
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public final String create(final ModelMap model) {
		logger.info("create be called ");
		model.addAttribute(REGISTER, new Register());
		return "/create";
	}

	/**
	 * Activate the account with the given activation key.
	 *
	 * @param key the activation key
	 * @param modelMap the model map
	 * @return the view name
	 */
	@RequestMapping(value = "/activate/{key}")
	public final String activate(@PathVariable("key") final String key,
			final ModelMap modelMap) {

		final boolean status = userDetailsService.activateUser(key);

		if (!status) {
			modelMap.put("error", true);
		}

		return "/activate";
	}
	private static final int DEFAULT_EXPIRATION = 3600;
	/**
	 * Handle the create account form submission.
	 *
	 * @param register the register form bean
	 * @param binding the binding result
	 * @param request the HTTP servlet request
	 * @return the path
	 */
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public final String submit(
			@ModelAttribute(REGISTER) @Valid final Register register,
			final BindingResult binding, final HttpServletRequest request) {

		if (binding.hasErrors()) {
			return "create";
		}
		if(!vaildUser()){
			binding.addError(new FieldError(REGISTER, "username",
			"YOUR GOOGLE ACCOUNT HAS PROBLEM"));
			return "create";
		}
		logger.info("submit be called");
		final UserAccount user = new UserAccount(register.getUsername());
		user.setDisplayName(register.getDisplayName());
		user.setEmail(register.getEmail());
		user.setPassword(passwordEncoder.encodePassword(
				register.getPassword(), user.getSalt()));
		try {
			UserAccount duser =userAccountService.loadUserByUsername(user.getUsername());
			if(duser!=null){
				throw new DuplicateUserException();
			}else{
				user.setEnabled(true);
				userAccountService.save(user);
				getMemcacheService().put(user.getUsername(), user,
						Expiration.byDeltaSeconds(DEFAULT_EXPIRATION));
			}
		} catch (DuplicateUserException e) {
			binding.addError(new FieldError(REGISTER, "username",
					"An account already exists with this username."));
			return "create";
		}
		return "/createSuccess";
	}
	/**
	 * 用来验证用户是否可用
	 * */
	private boolean vaildUser(){
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		if(user!=null&&"chch1020@gmail.com".equals(user.getEmail())){
			return true;
		}else{
			return false;
		}

	}
}
